const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { userModel } = require('../model/db');

router.post('/login', async (req, res) => {
    try {
        const { account, password } = req.body;
        
        // 参数验证
        if (!account || !password) {
            return res.status(400).json({ code: 400, message: '账号和密码不能为空' });
        }

        // 查询用户（支持用户名/手机/邮箱登录）
        const user = await userModel.findOne({
            $or: [
                { userName: account },
                { phone: account },
                { email: account }
            ]
        });

        if (!user) {
            return res.status(401).json({ code: 401, message: '用户不存在' });
        }

        // 验证密码
        const isMatch = await bcrypt.compare(password, user.pwd);
        if (!isMatch) {
            return res.status(401).json({ code: 401, message: '密码错误' });
        }

        // 生成JWT
        const token = jwt.sign(
            { userId: user._id }, 
            process.env.JWT_SECRET || 'your_secret_key', 
            { expiresIn: '8h' }
        );

        res.json({ 
            code: 200, 
            data: {
                token,
                userInfo: {
                    userId: user._id,
                    userName: user.userName,
                    avatar: user.avatar
                }
            }
        });

    } catch (error) {
        console.error('登录错误:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

module.exports = router;